package service

import (
	"fmt"
	"github.com/gin-gonic/gin"
	common "monitor_serve/commons/jwt"
	"monitor_serve/initialize"
	"monitor_serve/model"
	"net/http"
)

func CreateUser(c *gin.Context) {
	// 定义用户的结构体
	type User struct {
		Username string `json:"username"`
		Password string `json:"password"`
		Customer string `json:"customer"`
		UserId   int    `json:"userId"`
	}
	var user User
	if err := c.ShouldBind(&user); err != nil { // 修改这里
		fmt.Println("创建用户失败:", err)
		c.JSON(http.StatusBadRequest, gin.H{"error": "Invalid request"})
		return
	}
	if err := createUserService(user.Username, user.Password, user.Customer, user.UserId); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": "User create failed"})
		return // 添加返回语句，避免在错误时继续执行
	}
	c.JSON(http.StatusOK, gin.H{"message": "User created successfully"})
}

// 创建用户
func createUserService(name string, password string, customer string, userId int) error {
	user := model.User{
		Username: name,
		Password: password,
		Customer: customer,
		UserId:   userId,
	}
	tx := initialize.DB.Model(&user).Create(&user)
	if tx.Error != nil {
		return tx.Error
	}
	return nil
}

// 用户登录
func JWTLogin(c *gin.Context) {
	var userCredentials struct {
		Username string `json:"username" binding:"required"`
		Password string `json:"password" binding:"required"`
	}
	if err := c.ShouldBindJSON(&userCredentials); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": "Invalid request"})
		return
	}

	//查询数据中的信息
	var user model.User
	if result := initialize.DB.Where("username = ?", userCredentials.Username).First(&user); result.Error != nil {
		c.JSON(http.StatusBadRequest, gin.H{"code": 401, "error": "Authentication failed"})
		return
	}
	if userCredentials.Password != user.Password {
		c.JSON(http.StatusBadRequest, gin.H{"code": 401, "error": "Authentication failed "})
		return
	}

	token, err := common.GenerateToken(userCredentials.Username)
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to generate token"})
		return
	}

	c.JSON(http.StatusOK, gin.H{"code": 200, "msg": "登录成功", "token": token, "userId": user.UserId, "customer": user.Customer})
}
